package com.banciyuan.bcywebview.biz.groupdetail;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.text.SpannableString;
import android.text.TextUtils;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.GroupApi;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.factory.ForumThreadFactory;
import com.banciyuan.bcywebview.base.helper.ProgressbarHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.helper.timelinedatacenter.TimelineLikeHelper;
import com.banciyuan.bcywebview.base.util.BaseObserver;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshBase;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshListView;
import com.banciyuan.bcywebview.base.view.tag.TagView;
import com.banciyuan.bcywebview.base.view.textview.ExpandedTextView;
import com.banciyuan.bcywebview.base.view.textview.FocusButton;
import com.banciyuan.bcywebview.base.view.toast.MyToast;
import com.banciyuan.bcywebview.biz.circles.smooth.CircleSmoothActivity;
import com.banciyuan.bcywebview.biz.circles.smooth.CircleTagSmoothActivity;
import com.banciyuan.bcywebview.biz.detail.complex.ComplexDetailActivity;
import com.banciyuan.bcywebview.biz.event.EventDetailActivity;
import com.banciyuan.bcywebview.biz.groupdetail.info.TeamInfoActivity;
import com.banciyuan.bcywebview.biz.main.group.groupselect.GroupSelectActivity;
import com.banciyuan.bcywebview.biz.picshow.PostPictureActivity;
import com.banciyuan.bcywebview.biz.share.ShareActivity;
import com.banciyuan.bcywebview.biz.web.WebActivity;
import com.banciyuan.bcywebview.biz.write.photoselecotor.util.CommonUtils;
import com.banciyuan.bcywebview.biz.write.write.WriteActivity;
import com.banciyuan.bcywebview.utils.common.UIUtils;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.CommonApiUtils;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.banciyuan.bcywebview.utils.regex.MatchFilterImpl;
import com.banciyuan.bcywebview.utils.regex.MyLinkfy;
import com.banciyuan.bcywebview.utils.regex.MyRegex;
import com.banciyuan.bcywebview.utils.string.StringUtil;
import com.banciyuan.bcywebview.utils.string.UnderLineUtil;
import com.banciyuan.bcywebview.utils.universalimageloader.core.ImageLoader;
import com.banciyuan.bcywebview.utils.universalimageloader.utils.ImageOptions;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.daoexample.model.ForumThread;
import de.greenrobot.daoexample.model.Multi;
import de.greenrobot.daoexample.model.TagDetail;
import de.greenrobot.daoexample.model.Team;

/**
 * Created by hy on 2015/7/14.
 */
public class NewTeamDetailActivity extends BaseActivity implements View.OnClickListener {

    private final static int GOPUBLISH = 200;
    public final static int TEAMDETAIL_ACTIVITY = 10011;

    private PullToRefreshListView refreshView;
    private ListView lv;

    private ProgressbarHelper mProgressbarHelper;
    private View mProgressbarView;

    private NewTeamDetailAdapter madapter;
    private ExpandedTextView tvGroupIntro;
    private TextView tvGroupTitle;

    private View floatIndicator;
    private TextView joinnum;
    private TextView joinnumFloat;

    private TextView tvSortByTime;
    private TextView tvSortByDing;
    private TextView tvSortByCreate;

    private TextView tvSortByTimeFloat;
    private TextView tvSortByDingFloat;
    private TextView tvSortByCreateFloat;

    private View updateIndicator;
    private View dingIndicator;
    private View createIndicator;

    private View updateIndicatorFloat;
    private View dingIndicatorFloat;
    private View createIndicatorFloat;

    private FocusButton tvMarkStatus;
    private TextView titleAlpha;
    private TextView titleHeader;
    private TextView share_tv;
    private TagView tagarea;
    private ImageLoader imageLoader;
    private LinearLayout llImages;
    private View groupTitle;
    private View viewAddTag;
    private LinearLayout llRelaTopic;
    private View relaTopicContainer;
    private TextView tvRecommend;
    private ImageView ivRecommend;
    private TextView focusNums;
    private FocusButton floatFocusButton;

    private RequestQueue mQueue;
    private Response.ErrorListener onError;

    private boolean loading = false;
    private boolean timeHasMore = true;
    private boolean dingHasMore = true;
    private boolean createHasMore = true;
    private Team team;
    private String isMember;
    private int currentItem = 0;
    private int timePage = 1;
    private int dingPage = 1;
    private int createPage = 1;
    protected String mGid = "";
    private List<ForumThread> mTimeList = new ArrayList<>();
    private List<ForumThread> mDingList = new ArrayList<>();
    private List<ForumThread> mCreateList = new ArrayList<>();
    private String position;
    private String current_page;
    private View lockedView;
    private View teamInfoEntryView;
    private View header;

    private int header_height;
    private boolean mLastItemVisible;

    public static final String TEAMDETAIL_CREATE = "1";
    public static final String TEAMDETAIL_TIME = "0";
    private LayoutInflater layoutInflater;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_newteamdetail);
        initArgs();
        initProgressbar();
        initUi();
        initAction();
        if (TEAMDETAIL_CREATE.equals(current_page)) {
            currentItem = 1;
            changeSortStyle(1);
            initCreateData(false);
        } else if (TEAMDETAIL_TIME.equals(current_page)) {
            currentItem = 0;
            changeSortStyle(0);
            initTimeData(false);
        } else {
            currentItem = 2;
            changeSortStyle(2);
            initDingData(false);
        }
        getTeamDetail();
    }

    @Override
    protected void initArgs() {
        Intent intent = getIntent();
        mQueue = VolleyQueue.getRquest(this);
        imageLoader = ImageLoader.getInstance();
        mGid = intent.getStringExtra(gotoUtil.INTENT_VALUE_ONE);
        position = intent.getStringExtra(gotoUtil.INTENT_VALUE_THREE);
        current_page = intent.getStringExtra(gotoUtil.INTENT_VALUE_FOUR);

        onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                loading = false;
                mProgressbarHelper.onFailed();
            }
        };
        layoutInflater = LayoutInflater.from(this);
    }


    @Override
    protected void initProgressbar() {
        mProgressbarView = findViewById(R.id.base_progressbar);
        mProgressbarHelper = new ProgressbarHelper(mProgressbarView);
        mProgressbarHelper.setActionCallbacks(new ProgressbarHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                mProgressbarHelper.onLoading();
                getTeamDetail();
                initDingData(false);
            }
        });
        mProgressbarHelper.onLoading();
    }

    @Override
    protected void initUi() {
        refreshView = (PullToRefreshListView) findViewById(R.id.refresh_lv);
        lv = refreshView.getRefreshableView();
        tvRecommend = (TextView) findViewById(R.id.recommend_tv);
        ivRecommend = (ImageView) findViewById(R.id.recommend_iv);
        floatFocusButton = (FocusButton) findViewById(R.id.float_focus_click);
        header = View.inflate(this, R.layout.newteamdetail_header, null);

        titleHeader = (TextView) findViewById(R.id.tv_title_header);
        share_tv = (TextView) findViewById(R.id.invited_tv);
        lockedView = findViewById(R.id.locked_view);

        tvSortByTime = (TextView) header.findViewById(R.id.tv_sort_by_update);
        tvSortByDing = (TextView) header.findViewById(R.id.tv_sort_by_ding);
        tvSortByCreate = (TextView) header.findViewById(R.id.tv_sort_by_create);
        focusNums = (TextView) header.findViewById(R.id.focus_num);

        updateIndicator = header.findViewById(R.id.update_indicator);
        dingIndicator = header.findViewById(R.id.ding_indicator);
        createIndicator = header.findViewById(R.id.create_indicator);

        joinnum = (TextView) header.findViewById(R.id.member_num);

        tvSortByTimeFloat = (TextView) findViewById(R.id.tv_sort_by_update_float);
        tvSortByDingFloat = (TextView) findViewById(R.id.tv_sort_by_ding_float);
        tvSortByCreateFloat = (TextView) findViewById(R.id.tv_sort_by_create_float);

        updateIndicatorFloat = findViewById(R.id.update_indicator_float);
        dingIndicatorFloat = findViewById(R.id.ding_indicator_float);
        createIndicatorFloat = findViewById(R.id.create_indicator_float);

        floatIndicator = findViewById(R.id.rl_group_indicator_float);
        joinnumFloat = (TextView) findViewById(R.id.member_num_float);

        tvMarkStatus = (FocusButton) header.findViewById(R.id.focus_click);
        tvGroupIntro = (ExpandedTextView) header.findViewById(R.id.tv_group_intro);

        tvGroupTitle = (TextView) header.findViewById(R.id.tv_group_title);

        tagarea = (TagView) header.findViewById(R.id.tag_area);
        llImages = (LinearLayout) header.findViewById(R.id.ll_images);
        groupTitle = header.findViewById(R.id.rl_group_tag_title);
        viewAddTag = header.findViewById(R.id.tv_add_tag);
        lv.addHeaderView(header);
        teamInfoEntryView = findViewById(R.id.iv_go_team_info_top);
        llRelaTopic = (LinearLayout) header.findViewById(R.id.ll_rela_topic);
        relaTopicContainer = header.findViewById(R.id.relatopic_container);
        titleAlpha = (TextView) findViewById(R.id.tv_title_alpha);

        titleHeader.setText(getString(R.string.teamdetail_name));

        registerForContextMenu(tvGroupIntro);
        registerForContextMenu(tvGroupTitle);

    }

    @Override
    protected void initAction() {
        findViewById(R.id.recommend_click).setOnClickListener(this);
        findViewById(R.id.focus_click).setOnClickListener(this);
        tvSortByTime.setOnClickListener(this);
        tvSortByDing.setOnClickListener(this);
        tvSortByCreate.setOnClickListener(this);
        tvSortByTimeFloat.setOnClickListener(this);
        tvSortByDingFloat.setOnClickListener(this);
        tvSortByCreateFloat.setOnClickListener(this);
        floatFocusButton.setOnClickListener(this);
        groupTitle.setOnClickListener(this);
        header.findViewById(R.id.rl_go_more).setOnClickListener(this);
        findViewById(R.id.rl_bottom).setOnClickListener(this);
        teamInfoEntryView.setOnClickListener(this);
        findViewById(R.id.back).setOnClickListener(this);
        tvGroupIntro.setOnClickListener(this);
        lockedView.findViewById(R.id.tv_post_lock_link).setOnClickListener(this);
        share_tv.setOnClickListener(this);

        refreshView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                processRefresh();
            }
        });

        lv.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    if (mLastItemVisible) {
                        processLast();
                    }
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                mLastItemVisible = (totalItemCount > 0) && (firstVisibleItem + visibleItemCount >= totalItemCount - 1);
                View firstVisibleView = view.getChildAt(0);
                if (null == firstVisibleView) return;
                int top = Math.abs(firstVisibleView.getTop());
                int height = Math.abs(firstVisibleView.getTop()) + UIUtils.dip2px(38, NewTeamDetailActivity.this);
                if (firstVisibleItem == 1) {
                    float alpha = (float) (top / 4 * 0.01);
                    if (top > 0) {
                        titleHeader.setVisibility(View.GONE);
                        titleAlpha.setVisibility(View.VISIBLE);
                        titleAlpha.setAlpha(alpha);
                    }
                } else if (firstVisibleItem == 0) {
                    titleHeader.setVisibility(View.VISIBLE);
                    titleAlpha.setVisibility(View.GONE);
                }

                if (floatIndicator.getVisibility() == View.GONE && header_height != 0 && firstVisibleItem == 1 && height >= header_height) {
                    floatIndicator.setVisibility(View.VISIBLE);
                    floatFocusButton.setVisibility(View.VISIBLE);
                    teamInfoEntryView.setVisibility(View.GONE);
                } else if (floatIndicator.getVisibility() == View.VISIBLE && header_height != 0 && firstVisibleItem == 1 && height < header_height) {
                    floatIndicator.setVisibility(View.GONE);
                    floatFocusButton.setVisibility(View.GONE);
                    teamInfoEntryView.setVisibility(View.VISIBLE);
                } else if (firstVisibleItem >= 2 && floatIndicator.getVisibility() == View.GONE) {
                    floatIndicator.setVisibility(View.VISIBLE);
                    floatFocusButton.setVisibility(View.VISIBLE);
                    teamInfoEntryView.setVisibility(View.GONE);

                }
            }
        });
    }

    private void processRefresh() {
        switch (currentItem) {
            case 0:
                if (!loading) {
                    timePage = 1;
                    loading = true;
                    timeHasMore = true;
                    initTimeData(false);
                }
                break;
            case 1:
                if (!loading) {
                    createPage = 1;
                    loading = true;
                    createHasMore = true;
                    initCreateData(false);
                }
                break;
            case 2:
                if (!loading) {
                    dingPage = 1;
                    loading = true;
                    dingHasMore = true;
                    initDingData(false);
                }
                break;
        }
        getTeamDetail();
    }

    private void processLast() {
        switch (currentItem) {
            case 0:
                if (timeHasMore) {
                    timePage++;
                    initTimeData(true);
                } else {
                    loading = false;
                }
                break;
            case 1:
                if (createHasMore) {
                    loading = true;
                    createPage++;
                    initCreateData(true);
                } else {
                    loading = false;
                }
                break;
            case 2:
                if (dingHasMore) {
                    loading = true;
                    dingPage++;
                    initDingData(true);
                } else {
                    loading = false;
                }
                break;
        }
    }

    private void initTimeData(final boolean last) {
        loading = true;
        List<BcyPair> paramsList = new ArrayList<>();
        paramsList.add(new BcyPair(HttpUtils.INDEX_P, timePage + ""));
        paramsList.add(new BcyPair(HttpUtils.GID, mGid));
        paramsList.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(this).getToken()));
        Map<String, String> map = HttpUtils.getData(paramsList);
        String url = HttpUtils.BASE_URL + GroupApi.getListposts();
        Response.Listener<String> onTimeSuccess = new Response.Listener<String>() {

            @Override
            public void onResponse(String s) {
                dealTimeDetailJson(s, last);
            }
        };

        OnErrorProxy errorProxy = new OnErrorProxy(onError, onTimeSuccess, url, NewTeamDetailActivity.this, map);
        StringRequestParam getUserdataRequest = new StringRequestParam(Request.Method.POST, url, map, onTimeSuccess, errorProxy);
        mQueue.add(getUserdataRequest);
    }

    private void initDingData(final boolean last) {
        List<BcyPair> paramsList = new ArrayList<>();
        paramsList.add(new BcyPair(HttpUtils.INDEX_P, dingPage + ""));
        paramsList.add(new BcyPair(HttpUtils.GID, mGid));
        paramsList.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(this).getToken()));
        paramsList.add(new BcyPair(HttpUtils.TYPE, "ding"));
        Map<String, String> map = HttpUtils.getData(paramsList);
        String url = HttpUtils.BASE_URL + GroupApi.getListposts();
        Response.Listener<String> onDingSuccess = new Response.Listener<String>() {

            @Override
            public void onResponse(String s) {
                dealDingDetailJson(s, last);
            }
        };
        OnErrorProxy errorProxy = new OnErrorProxy(onError, onDingSuccess, url, NewTeamDetailActivity.this, map);
        StringRequestParam getUserdataRequest = new StringRequestParam(Request.Method.POST, url, map, onDingSuccess, errorProxy);
        mQueue.add(getUserdataRequest);
    }

    private void initCreateData(final boolean last) {
        List<BcyPair> paramsList = new ArrayList<>();
        paramsList.add(new BcyPair(HttpUtils.INDEX_P, createPage + ""));
        paramsList.add(new BcyPair(HttpUtils.GID, mGid));
        paramsList.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(this).getToken()));
        paramsList.add(new BcyPair(HttpUtils.TYPE, "create"));
        Map<String, String> map = HttpUtils.getData(paramsList);
        String url = HttpUtils.BASE_URL + GroupApi.getListposts();
        Response.Listener<String> onCreateSuccess = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                dealCreateDetailJson(s, last);
            }
        };
        OnErrorProxy errorProxy = new OnErrorProxy(onError, onCreateSuccess, url, NewTeamDetailActivity.this, map);
        StringRequestParam getUserdataRequest = new StringRequestParam(Request.Method.POST, url, map, onCreateSuccess, errorProxy);
        mQueue.add(getUserdataRequest);
    }

    private void dealCreateDetailJson(String jsonResult, boolean last) {
        if (StatusCodeUtils.dealStatusCode(jsonResult, this)) {
            try {
                JSONObject response = new JSONObject(jsonResult);
                List<ForumThread> tempList = ForumThreadFactory.createForumThread(response.getJSONArray(HttpUtils.UPLOAD_DATA));
                processCreateFinalData(tempList, last);
            } catch (Exception e) {
                loading = false;
            }
        } else {
            loading = false;
        }
    }

    private void dealDingDetailJson(String jsonResult, boolean last) {
        if (StatusCodeUtils.dealStatusCode(jsonResult, this)) {
            try {
                JSONObject response = new JSONObject(jsonResult);
                List<ForumThread> tempList = ForumThreadFactory.createForumThread(response.getJSONArray(HttpUtils.UPLOAD_DATA));
                processDingFinalData(tempList, last);
            } catch (Exception e) {
                e.printStackTrace();
                loading = false;
            }
        } else {
            loading = false;
        }
    }

    private void dealTimeDetailJson(String jsonResult, boolean last) {
        if (StatusCodeUtils.dealStatusCode(jsonResult, this)) {
            try {
                JSONObject response = new JSONObject(jsonResult);
                List<ForumThread> tempList = ForumThreadFactory.createForumThread(response.getJSONArray(HttpUtils.UPLOAD_DATA));
                processTimeFinalData(tempList, last);
            } catch (Exception e) {
                loading = false;
            }
        } else {
            loading = false;
        }
    }

    private void processTimeFinalData(List<ForumThread> templist, boolean last) {
        if (timePage == 1) {
            mTimeList.clear();
        }
        mTimeList.addAll(templist);
        if (null == madapter) {
            madapter = new NewTeamDetailAdapter(this, mTimeList);
            lv.setAdapter(madapter);
            madapter.setListView(lv);
        } else {
            madapter.setData(mTimeList);
            madapter.notifyDataSetChanged();
        }
        int state = mProgressbarHelper.getState();
        if (state == ProgressbarHelper.PROGRESS_STATE_LOADING) {
            mProgressbarHelper.onSuccess();
        }
        loading = false;
        jumpToTop(last);
    }

    private void processDingFinalData(List<ForumThread> templist, boolean last) {
        if (dingPage == 1) {
            mDingList.clear();
        }
        mDingList.addAll(templist);
        if (null == madapter) {
            madapter = new NewTeamDetailAdapter(this, mDingList);
            lv.setAdapter(madapter);
            madapter.setListView(lv);
        } else {
            madapter.setData(mDingList);
            madapter.notifyDataSetChanged();
        }
        int state = mProgressbarHelper.getState();
        if (state == ProgressbarHelper.PROGRESS_STATE_LOADING) {
            mProgressbarHelper.onSuccess();
        }
        loading = false;
        jumpToTop(last);

    }

    private void processCreateFinalData(List<ForumThread> templist, boolean last) {
        if (createPage == 1) {
            mCreateList.clear();
        }
        mCreateList.addAll(templist);
        if (null == madapter) {
            madapter = new NewTeamDetailAdapter(this, mCreateList);
            lv.setAdapter(madapter);
            madapter.setListView(lv);
        } else {
            madapter.setData(mCreateList);
            madapter.notifyDataSetChanged();
        }
        int state = mProgressbarHelper.getState();
        if (state == ProgressbarHelper.PROGRESS_STATE_LOADING) {
            mProgressbarHelper.onSuccess();
        }
        loading = false;
        jumpToTop(last);

    }


    public void getTeamDetail() {
        Response.Listener<String> onSuccess = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    JSONObject result = new JSONObject(response);
                    String status = result.getString(HttpUtils.UPLOAD_STATUS);
                    if (status.equals("1")) {
                        processGroupDetail(response);
                        refreshView.onRefreshComplete();
                    } else if (status.equals("4050")) {
                        lockedView.setVisibility(View.VISIBLE);
                        teamInfoEntryView.setVisibility(View.GONE);
                        mProgressbarHelper.onSuccess();
                        refreshView.onRefreshComplete();
                    } else {
                        Object data = result.get(HttpUtils.UPLOAD_DATA);
                        MyToast.show(NewTeamDetailActivity.this, data.toString());
                        mProgressbarHelper.onFailed();
                        refreshView.onRefreshComplete();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    mProgressbarHelper.onFailed();
                    refreshView.onRefreshComplete();
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                loading = false;
                mProgressbarHelper.onFailed();
                refreshView.onRefreshComplete();
            }
        };
        CommonApiUtils.getTeamInfo(this, mQueue, onSuccess, onError, mGid);
    }

    public void processGroupDetail(String result) {
        if (!TextUtils.isEmpty(result)) {
            try {
                JSONObject jsonResult = new JSONObject(result).getJSONObject("data");
                Gson gson = new Gson();
                team = gson.fromJson(jsonResult.getString("group"), Team.class);
                if (jsonResult.has("is_member")) {
                    isMember = jsonResult.getString("is_member");
                }
                if (jsonResult.has("is_creator")) {
                    team.setIsCreator(String.valueOf(jsonResult.getBoolean("is_creator")));
                }
                team.setAdmin(jsonResult.getJSONObject("admin").getString("name"));
                processGroupDetailData();
                processRelaTeam(jsonResult, gson);

                header.measure(
                        View.MeasureSpec.makeMeasureSpec(CommonUtils.getWidthPixels(this), View.MeasureSpec.AT_MOST),
                        View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
                header_height = header.getMeasuredHeight();

                BaseObserver.getInstance().notifyWatchers(BaseObserver.GROUP_COUNT_CLEAR, team.getGid());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void processRelaTeam(JSONObject jsonResult, Gson gson) throws Exception {
        if (jsonResult.has("rela")) {
            List<Team> relaTeam = gson.fromJson(jsonResult.getString("rela"), new TypeToken<List<Team>>() {
            }.getType());
            processRelaTeamView(relaTeam);
        } else {
            relaTopicContainer.setVisibility(View.GONE);
        }
    }

    private void processRelaTeamView(List<Team> relaTeams) {
        if (relaTeams.isEmpty() && team.getcRecommendCircle().isEmpty()) {
            relaTopicContainer.setVisibility(View.GONE);
            return;
        }
        relaTopicContainer.setVisibility(View.VISIBLE);

        llRelaTopic.removeAllViews();
        if (!team.getcRecommendCircle().isEmpty()) {
            processSingleCircleTeam(team.getcRecommendCircle().get(0));

        }
        for (int i = 0; i < relaTeams.size(); i++) {
            processSingleRelaTeam(relaTeams.get(i));
        }

        for (int i = 1; i < team.getcRecommendCircle().size(); i++) {
            processSingleCircleTeam(team.getcRecommendCircle().get(i));
        }

        View viewEnterHotCircle = layoutInflater.inflate(R.layout.default_enter_relacircle_item, llRelaTopic, false);
        viewEnterHotCircle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                gotoUtil.gotoAct(NewTeamDetailActivity.this, GroupSelectActivity.class, 0);
            }
        });
        llRelaTopic.addView(viewEnterHotCircle);
    }

    private void processSingleCircleTeam(final TagDetail tagDetail) {
        View viewTopicItem = layoutInflater.inflate(R.layout.rela_topic_item, llRelaTopic, false);
        ImageView ivTopicCover = (ImageView) viewTopicItem.findViewById(R.id.iv_topic_cover);
        TextView tvTopicName = (TextView) viewTopicItem.findViewById(R.id.tv_topic_name);
        View viewCircleEntrance = viewTopicItem.findViewById(R.id.tv_circle_entrance);
        viewCircleEntrance.setVisibility(View.VISIBLE);
        imageLoader.displayImage(tagDetail.getCover(), ivTopicCover, ImageOptions.options);
        tvTopicName.setMaxLines(1);
        if ("work".equals(tagDetail.getType())) {
            tvTopicName.setText(tagDetail.getWork());
            viewTopicItem.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(NewTeamDetailActivity.this, CircleSmoothActivity.class);
                    intent.putExtra(gotoUtil.INTENT_VALUE_ONE, tagDetail.getWork());
                    intent.putExtra(gotoUtil.INTENT_VALUE_TWO, tagDetail.getWid());
                    intent.putExtra("from", 2);
                    startActivity(intent);
                }
            });
        } else if ("tag".equals(tagDetail.getType())) {
            tvTopicName.setText(tagDetail.getTag_name());
            viewTopicItem.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(NewTeamDetailActivity.this, CircleTagSmoothActivity.class);
                    intent.putExtra(gotoUtil.INTENT_VALUE_ONE, tagDetail.getTag_name());
                    intent.putExtra(gotoUtil.INTENT_VALUE_TWO, tagDetail.getTag_id());
                    intent.putExtra("from", 2);
                    startActivity(intent);
                }
            });
        } else if ("event".equals(tagDetail.getType())) {
            tvTopicName.setText(tagDetail.getTag_name());
            viewTopicItem.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    gotoUtil.gotoAct(NewTeamDetailActivity.this, EventDetailActivity.class, tagDetail.getEvent_id());
                }
            });
        }
        llRelaTopic.addView(viewTopicItem);
    }

    private void processSingleRelaTeam(final Team relaTeam) {
        View viewTopicItem = layoutInflater.inflate(R.layout.rela_topic_item, llRelaTopic, false);
        ImageView ivTopicCover = (ImageView) viewTopicItem.findViewById(R.id.iv_topic_cover);
        TextView tvTopicName = (TextView) viewTopicItem.findViewById(R.id.tv_topic_name);
        View viewCircleEntrance = viewTopicItem.findViewById(R.id.tv_circle_entrance);
        viewCircleEntrance.setVisibility(View.GONE);
        if (!TextUtils.isEmpty(relaTeam.getImg_src()))
            imageLoader.displayImage(relaTeam.getImg_src(), ivTopicCover, ImageOptions.options);
        else
            ivTopicCover.setImageResource(R.drawable.recommend_topic_default);
        tvTopicName.setText(Html.fromHtml(relaTeam.getName()));
        tvTopicName.setMaxLines(3);
        viewTopicItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                gotoUtil.gotoAct(NewTeamDetailActivity.this, NewTeamDetailActivity.class, relaTeam.getGid());
            }
        });
        llRelaTopic.addView(viewTopicItem);
    }

    private void processGroupDetailData() {
        if (team != null) {
            if (!TextUtils.isEmpty(team.getName())) {
                titleAlpha.setText(Html.fromHtml(team.getName()));
                tvGroupTitle.setText(Html.fromHtml(team.getName()));
            }
            if (!TextUtils.isEmpty(team.getPost_num())) {
                joinnum.setText(String.format(getString(R.string.person_join_group_unit_2), team.getPost_num()));
                joinnumFloat.setText(String.format(getString(R.string.person_join_group_unit_2), team.getPost_num()));
            }
        }
        processIntro();
        processMarkData();
        processRecommendData();
        processRecommendCircleData();
        processTagData();
        processImageData();
    }

    private void processRecommendCircleData() {
        List<TagDetail> recommendCircle = new ArrayList<>();
        addWorkToRecommendTag(recommendCircle);
        if (null != team.getTags()) {
            for (int i = 0; i < team.getTags().size(); i++) {
                TagDetail tagDetail = team.getTags().get(i);
                if (isLegalRecommendCircle(tagDetail)) {
                    recommendCircle.add(tagDetail);
                }
            }
        }
        team.setcRecommendCircle(recommendCircle);
    }

    private boolean isLegalRecommendCircle(TagDetail tagDetail) {
        try {
            return "event".equals(tagDetail.getType()) || !TextUtils.isEmpty(tagDetail.getGroup_count()) && Integer.valueOf(tagDetail.getGroup_count()) > 10;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    private SpannableString processIntroFunction(String text) {
        SpannableString spannableString = StringUtil.setAtUser(text, team.getAt_users(), NewTeamDetailActivity.this);
        MyLinkfy.addLinks(spannableString, MyRegex.plist.get(0), "bcyapp_", new MatchFilterImpl(), null);
        UnderLineUtil.DisUnderLine(NewTeamDetailActivity.this, spannableString);
        return spannableString;
    }

    private void processIntro() {
        if (!TextUtils.isEmpty(team.getMember_num())) {
            focusNums.setText(String.format(getString(R.string.focus_mount_unit), team.getMember_num()));
        }
        tvGroupIntro.setMaxLines(3);
        if (!TextUtils.isEmpty(team.getIntro())) {
            ((View) (tvGroupIntro.getParent())).setVisibility(View.VISIBLE);
            tvGroupIntro.setText(processIntroFunction(StringUtil.htmlDecoder(team.getIntro())), true, new ExpandedTextView.OnProcessClick() {
                @Override
                public SpannableString onProcessSucc(CharSequence text) {
                    return processIntroFunction(text.toString());
                }
            }, new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    tvGroupIntro.setMaxLines(200);
                    header.measure(
                            View.MeasureSpec.makeMeasureSpec(CommonUtils.getWidthPixels(NewTeamDetailActivity.this), View.MeasureSpec.AT_MOST),
                            View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
                    header_height = header.getMeasuredHeight();
                }
            }, R.string.open_talk_no_format, 3);
        } else {
            tvGroupIntro.setVisibility(View.GONE);
        }
    }

    private void processMarkData() {
        if (StringUtil.notNullEqual(isMember, "true")) {
            tvMarkStatus.setSelected(true);
            floatFocusButton.setSelected(true);
        } else {
            tvMarkStatus.setSelected(false);
            floatFocusButton.setSelected(false);
        }
    }

    private void processRecommendData() {
        if (StringUtil.getBoolean(team.getHave_tuijian())) {
            tvRecommend.setText(getString(R.string.all_recommended));
            ivRecommend.setImageResource(R.drawable.has_recommend_talk);
        } else {
            tvRecommend.setText(getString(R.string.recommend_question));
            ivRecommend.setImageResource(R.drawable.talk_recommend);
        }
    }

    private void processImageData() {
        List<Multi> multi = team.getMulti();
        if (null == multi || multi.size() == 0) {
            llImages.setVisibility(View.GONE);
        } else {
            final List<String> imageUrls = new ArrayList<String>();
            for (int i = 0; i < multi.size(); i++) {
                imageUrls.add(multi.get(i).getOrigin());
            }
            llImages.setVisibility(View.VISIBLE);
            llImages.removeAllViews();
            for (int i = 0; i < multi.size(); i++) {
                View teamImage = View.inflate(this, R.layout.team_image, null);
                ImageView image = (ImageView) teamImage.findViewById(R.id.image);
                if (!multi.get(i).getOrigin().contains(".gif")) {
                    imageLoader.displayImage(multi.get(i).getOrigin(), image, ImageOptions.options, null, null, true);
                } else {
                    imageLoader.displayImage(multi.get(i).getOrigin(), image, ImageOptions.options, null, null, false);
                }
                final int finalI = i;
                image.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(NewTeamDetailActivity.this, PostPictureActivity.class);
                        intent.putStringArrayListExtra("imageUrls", (ArrayList<String>) imageUrls);
                        intent.putExtra("position", finalI);
                        startActivity(intent);
                    }
                });
                llImages.addView(teamImage);
            }
        }
    }

    private void processTagData() {
        List<TagDetail> tags = team.getTags();
        addWorkToRelaTag(tags);
        if (tags.size() == 0) {
            viewAddTag.setVisibility(View.VISIBLE);
            tagarea.setVisibility(View.GONE);
        } else {
            viewAddTag.setVisibility(View.GONE);
            tagarea.setVisibility(View.VISIBLE);
            tagarea.setTlist(tags);
            tagarea.setTagViewClick(new TagView.OnTagClickListener() {
                @Override
                public void onClick(TagDetail t) {
                    if ("work".equals(t.getType())) {
                        if (!TextUtils.isEmpty(t.getWid())) {
                            gotoUtil.gotoAct(NewTeamDetailActivity.this, CircleSmoothActivity.class, team.getWork(), team.getId(), 2);
                        }
                    } else if ("tag".equals(t.getType())) {
                        if (!StringUtil.notNullEqual(t.getShow_name(), "...")) {
                            Intent intent = new Intent(NewTeamDetailActivity.this, CircleTagSmoothActivity.class);
                            intent.putExtra(gotoUtil.INTENT_VALUE_ONE, t.getTag_name());
                            intent.putExtra("type", "tag");
                            intent.putExtra("from", 2);
                            startActivity(intent);
                        } else {
                            Intent intent = new Intent(NewTeamDetailActivity.this, GroupTagInfoActivity.class);
                            intent.putExtra(gotoUtil.INTENT_VALUE_TWO, team);
                            intent.putExtra(gotoUtil.INTENT_VALUE_ONE, mGid);
                            startActivity(intent);
                        }
                    } else if ("event".equals(t.getType())) {
                        gotoUtil.gotoAct(NewTeamDetailActivity.this, EventDetailActivity.class, t.getEvent_id());
                    }
                }
            });
        }
    }

    private void addWorkToRelaTag(List<TagDetail> tags) {
        if (!TextUtils.isEmpty(team.getWork())) {
            TagDetail tagDetail = new TagDetail();
            tagDetail.setWork(team.getWork());
            tagDetail.setTag_name(team.getWork());
            tagDetail.setWid(team.getId());
            tagDetail.setType("work");
            if (null != team.getPost_core())
                tagDetail.setCover(team.getPost_core().getCover());
            tags.add(0, tagDetail);
        }
    }

    private void addWorkToRecommendTag(List<TagDetail> tags) {
        if (!TextUtils.isEmpty(team.getId())) {
            TagDetail tagDetail = new TagDetail();
            tagDetail.setWork(team.getWork());
            tagDetail.setTag_name(team.getWork());
            tagDetail.setWid(team.getId());
            tagDetail.setType("work");
            if (null != team.getPost_core())
                tagDetail.setCover(team.getPost_core().getCover());
            tags.add(0, tagDetail);
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_sort_by_update:
            case R.id.tv_sort_by_update_float:
                setSelectUpdate(false);
                break;
            case R.id.tv_sort_by_create:
            case R.id.tv_sort_by_create_float:
                setSelectCreate(false);
                break;
            case R.id.tv_sort_by_ding:
            case R.id.tv_sort_by_ding_float:
                setSelectDing(false);
                break;
            case R.id.back:
                finish();
                break;
            case R.id.rl_bottom:
                Intent intent = new Intent(this, WriteActivity.class);
                intent.putExtra(gotoUtil.INTENT_VALUE_ONE, TEAMDETAIL_ACTIVITY);
                intent.putExtra(gotoUtil.INTENT_VALUE_TWO, mGid);
                startActivityForResult(intent, GOPUBLISH);
                break;
            case R.id.iv_go_team_info_top:
                Intent infoIntent = new Intent();
                infoIntent.putExtra(gotoUtil.INTENT_VALUE_ONE, mGid);
                infoIntent.putExtra(gotoUtil.INTENT_VALUE_TWO, team);
                infoIntent.setClass(NewTeamDetailActivity.this, TeamInfoActivity.class);
                startActivityForResult(infoIntent, 201);
                break;
            case R.id.focus_click:
                doFollow();
                break;
            case R.id.float_focus_click:
                doFollow();
                break;
            case R.id.rl_go_more:
            case R.id.rl_group_tag_title:
                intent = new Intent(NewTeamDetailActivity.this, GroupTagInfoActivity.class);
                intent.putExtra(gotoUtil.INTENT_VALUE_TWO, team);
                intent.putExtra(gotoUtil.INTENT_VALUE_ONE, mGid);
                startActivity(intent);
                break;
            case R.id.recommend_click:
                if (null == team) return;
                TimelineLikeHelper.doRecommendGroupTeam(this, mQueue, team.getGid(), team.getHave_tuijian(), new TimelineLikeHelper.TimelineSuccess() {
                    @Override
                    public void onTimelineSuccess() {
                        team.setHave_tuijian(String.valueOf(!Boolean.valueOf(team.getHave_tuijian())));
                        processRecommendData();
                    }
                });
                break;
            case R.id.invited_tv:
                goShare();
                break;
            case R.id.tv_post_lock_link:
                gotoUtil.gotoAct(getContext(), WebActivity.class, getString(R.string.lock_link));
                break;
            default:
                break;
        }
    }

    private void setSelectDing(boolean last) {
        currentItem = 2;
        changeSortStyle(2);
        if (null == mDingList || mDingList.size() <= 0) {
            initDingData(last);
        } else {
            if (null == madapter) {
                madapter = new NewTeamDetailAdapter(this, mDingList);
                lv.setAdapter(madapter);
                madapter.setListView(lv);
            } else {
                madapter.setData(mDingList);
                madapter.notifyDataSetChanged();
            }
            jumpToTop(last);
        }

    }

    private void setSelectCreate(boolean last) {
        currentItem = 1;
        changeSortStyle(1);
        if (null == mCreateList || mCreateList.size() <= 0) {
            initCreateData(last);
        } else {
            if (null == madapter) {
                madapter = new NewTeamDetailAdapter(this, mCreateList);
                lv.setAdapter(madapter);
                madapter.setListView(lv);
            } else {
                madapter.setData(mCreateList);
                madapter.notifyDataSetChanged();
            }
            jumpToTop(last);
        }

    }

    private void setSelectUpdate(boolean last) {
        currentItem = 0;
        changeSortStyle(0);
        if (null == mTimeList || mTimeList.size() <= 0) {
            initTimeData(last);
        } else {
            if (null == madapter) {
                madapter = new NewTeamDetailAdapter(this, mTimeList);
                lv.setAdapter(madapter);
                madapter.setListView(lv);
            } else {
                madapter.setData(mTimeList);
                madapter.notifyDataSetChanged();
            }
            jumpToTop(last);
        }
    }

    private void jumpToTop(final boolean last) {
        if (floatIndicator.getVisibility() == View.VISIBLE) {
            floatIndicator.post(new Runnable() {
                @Override
                public void run() {
                    if (!last) {
                        lv.setSelectionFromTop(2, UIUtils.dip2px(38, NewTeamDetailActivity.this));
                    }
                }
            });
        }
    }

    private void goShare() {
        if (team == null) return;
        Intent intent = new Intent(NewTeamDetailActivity.this, ShareActivity.class);
        intent.putExtra("showblock", false);
        intent.putExtra("showDelBtn", false);
        intent.putExtra("showWarnBtn", true);
        intent.putExtra("showCopyLink", true);
        intent.putExtra("showShare", true);
        intent.putExtra("is_group", true);
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("content", String.format(getString(R.string.share_talk), team.getPost_num(), team.getMember_num(), team.getGid()));
        map.put("title", String.format(getString(R.string.share_talk_title), team.getName()));
        map.put("url", "http://bcy.net/group/list/" + team.getGid());
        map.put("gid", team.getGid());
        intent.putExtra("map", map);
        startActivityForResult(intent, ComplexDetailActivity.GOSHARE);
        overridePendingTransition(R.anim.umeng_socialize_fade_in, R.anim.umeng_socialize_fade_out);
    }

    private void doFollow() {
        Response.Listener<String> onSuccess = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (StatusCodeUtils.dealStatusCode(response, NewTeamDetailActivity.this)) {
                    if (!StringUtil.notNullEqual(isMember, "true")) {
                        isMember = "true";
                        MyToast.show(NewTeamDetailActivity.this, getString(R.string.focus_succ));
                    } else {
                        isMember = "false";
                        MyToast.show(NewTeamDetailActivity.this, getString(R.string.cancle_focus_succ));
                    }
                    processMarkData();
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }
        };
        if (!StringUtil.notNullEqual(isMember, "true")) {
            CommonApiUtils.doTeamFollow(NewTeamDetailActivity.this, mQueue, onSuccess, onError, mGid);
        } else {
            CommonApiUtils.doTeamCancel(NewTeamDetailActivity.this, mQueue, onSuccess, onError, mGid);
        }
    }

    private void changeSortStyle(int selectedItem) {
        switch (selectedItem) {
            case 0:
                tvSortByTime.setSelected(true);
                tvSortByCreate.setSelected(false);
                tvSortByDing.setSelected(false);
                tvSortByTimeFloat.setSelected(true);
                tvSortByCreateFloat.setSelected(false);
                tvSortByDingFloat.setSelected(false);
                updateIndicator.setVisibility(View.VISIBLE);
                createIndicator.setVisibility(View.INVISIBLE);
                dingIndicator.setVisibility(View.INVISIBLE);
                updateIndicatorFloat.setVisibility(View.VISIBLE);
                createIndicatorFloat.setVisibility(View.INVISIBLE);
                dingIndicatorFloat.setVisibility(View.INVISIBLE);
                break;
            case 1:
                tvSortByTime.setSelected(false);
                tvSortByCreate.setSelected(true);
                tvSortByDing.setSelected(false);
                tvSortByTimeFloat.setSelected(false);
                tvSortByCreateFloat.setSelected(true);
                tvSortByDingFloat.setSelected(false);
                updateIndicator.setVisibility(View.INVISIBLE);
                createIndicator.setVisibility(View.VISIBLE);
                dingIndicator.setVisibility(View.INVISIBLE);
                updateIndicatorFloat.setVisibility(View.INVISIBLE);
                createIndicatorFloat.setVisibility(View.VISIBLE);
                dingIndicatorFloat.setVisibility(View.INVISIBLE);
                break;
            case 2:
                tvSortByTime.setSelected(false);
                tvSortByCreate.setSelected(false);
                tvSortByDing.setSelected(true);
                tvSortByTimeFloat.setSelected(false);
                tvSortByCreateFloat.setSelected(false);
                tvSortByDingFloat.setSelected(true);
                updateIndicator.setVisibility(View.INVISIBLE);
                createIndicator.setVisibility(View.INVISIBLE);
                dingIndicator.setVisibility(View.VISIBLE);
                updateIndicatorFloat.setVisibility(View.INVISIBLE);
                createIndicatorFloat.setVisibility(View.INVISIBLE);
                dingIndicatorFloat.setVisibility(View.VISIBLE);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 200:
                if (resultCode == RESULT_OK) {
                    setSelectCreate(false);
                    refreshView.setRefreshing();
                }
                break;
            case 201:

                break;
        }
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        try {
            menu.add(0, v.getId(), 0, getString(R.string.copy_paste));
            TextView textView = (TextView) v;
            ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
            ClipData clipData = ClipData.newPlainText("shareText", textView.getText().toString());
            clipboard.setPrimaryClip(clipData);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterForContextMenu(tvGroupIntro);
        unregisterForContextMenu(tvGroupTitle);
    }
}